package com.example.phone.ProductDetails;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.phone.Login.LoginActivity;
import com.example.phone.R;
import com.example.phone.base.BaseActivity;
import com.example.phone.base.MyApp;
import com.example.phone.base.RequestInterface;
import com.example.phone.base.ServerResponse;
import com.example.phone.bean.AddressItem;
import com.example.phone.bean.AddressList;
import com.example.phone.bean.Cart;
import com.example.phone.bean.Product;
import com.example.phone.bean.ShoppingCart;
import com.example.phone.bean.ShoppingCartList;
import com.example.phone.bean.User;
import com.example.phone.cart.CartFragment;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.loader.ImageLoader;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
//import q.rorbin.badgeview.QBadgeView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import static android.view.View.VISIBLE;
import static com.example.phone.base.RequestInterface.baseIp;

public class Detail extends BaseActivity {


    @BindView(R.id.detail_banner)
    Banner detailBanner;
    @BindView(R.id.tv_detail_price)
    TextView tvDetailPrice;
    @BindView(R.id.ll_detail_collect)
    LinearLayout llDetailCollect;
    @BindView(R.id.tv_detail_description)
    TextView tvDetailDescription;
    @BindView(R.id.tv_detail_address)
    TextView tvDetailAddress;
    @BindView(R.id.iv_detail_address_more)
    ImageView ivDetailAddressMore;
    @BindView(R.id.ll_detail_service)
    LinearLayout llDetailService;
    @BindView(R.id.ll_detail_store)
    LinearLayout llDetailStore;
    @BindView(R.id.ll_detail_cart)
    LinearLayout llDetailCart;
    @BindView(R.id.ll_detail_price_collect)
    LinearLayout llDetailPriceCollect;
    @BindView(R.id.tv_detail_AddToCart)
    TextView tvDetailAddToCart;
    @BindView(R.id.tv_detail_PurchaseNow)
    TextView tvDetailPurchaseNow;
    @BindView(R.id.tv_detail_chosen_size)
    TextView tvDetailChosenSize;
    @BindView(R.id.ll_detail_bottom)
    LinearLayout llDetailBottom;
    ImageView[] imageViews;



    public static final String baseImgPath = "http://" + baseIp + ":8080/PhoneShop/Images/";
    String [] imagePath;//用于存储图片链接
    BadgeView badgeView;//用于购物车上显示购物车中商品数量
    Detail thisActivty = this;
    private List<Cart> mShoppingCartList;
    CartFragment cartFragment = new CartFragment();
    MyApp myApp;//将信息从Application中取出
    int productId ;
    int userId ;
    User user;
    int num;
    @Override
    public void initData() {
        badgeView = new BadgeView(thisActivty);
        badgeView.setTargetView(thisActivty.findViewById(R.id.ll_detail_cart));
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);


    }

    @Override
    public int initLayout() {
        myApp = (MyApp) getApplication();//将信息从Application中取出
        user = myApp.getUser();
        Intent intent = getIntent();

        productId = intent.getIntExtra("productId", 0);
        getProductInfo(productId);

        if(user != null)
        {
            userId = user.getId();
            getShoppingCartList(userId);
            getAddress(userId);
        }
        return R.layout.activity_detail;
    }

    private void switchFragment(Fragment f) {
        FragmentManager fragmentM = getSupportFragmentManager();//管理对象
        FragmentTransaction trans = fragmentM.beginTransaction();//切换碎片
        llDetailBottom.setVisibility(View.GONE);
        trans.replace(R.id.detail, f);
        trans.commit();
    }
    @OnClick({R.id.ll_detail_collect, R.id.iv_detail_address_more, R.id.ll_detail_store,
            R.id.ll_detail_service, R.id.ll_detail_cart, R.id.tv_detail_AddToCart, R.id.tv_detail_PurchaseNow})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_detail_collect:
                toastShort("收藏");
                break;
            case R.id.iv_detail_address_more:
                toastShort("送至其他地址");
                break;
            case R.id.ll_detail_service:
                toastShort("客服");

                break;
            case R.id.ll_detail_store:
                toastShort("店铺");
                break;
            case R.id.ll_detail_cart:
                switchFragment(cartFragment);
                break;
            case R.id.tv_detail_AddToCart:
                toastShort("加入购物车");
                //首先判断该用户是否登录

                if(user == null){
                    toastShort("未登录");
                    goNextActivity(LoginActivity.class);
                    return;
                }
                else
                 {
                     userId = user.getId();
                    addToCart(productId, 1,userId);
                 }
                break;
            case R.id.tv_detail_PurchaseNow:
                toastShort("立即购买");
                //首先判断该用户是否登录
//                if(user == null){
//                    toastShort("未登录");
//                    goNextActivity(LoginActivity.class);
//                    return;
//                }
                //               else
                break;
        }
    }


    //设置轮播图
    private void initBanner(String [] imagePath) {
        List<String> images = new ArrayList<>();
        for(int i =0 ; i < imagePath.length; i++)
            images.add(imagePath[i]);
        detailBanner = findViewById(R.id.detail_banner);
        detailBanner.setImages(images);
        detailBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        detailBanner.setImageLoader(new ImageLoader() {
            @Override
            public void displayImage(Context context, Object path, ImageView imageView) {
                Glide.with(context).load(path).into(imageView);
            }
        });
        detailBanner.setDelayTime(99999999);
        detailBanner.start();
    }
//将链接前缀图片名称与拼接
    private String[] imagesPath(String [] arr, String str){
        for(int i =0 ; i < arr.length; i++)
            arr[i] = str + arr[i];
        return arr;
    }

    //根据productId来获取商品详情
    private void getProductInfo(int productId) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(RequestInterface.basePath)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RequestInterface.getProductDetail requestInterfaceProductDetail = retrofit.create(RequestInterface.getProductDetail.class);
        Call<ServerResponse<Product>> call = requestInterfaceProductDetail.getProductDetail(productId);
        call.enqueue(new Callback<ServerResponse<Product>>() {

            @Override
            public void onResponse(Call<ServerResponse<Product>> call, Response<ServerResponse<Product>> response) {

                Log.d("details", "成功");

                if (response.body() == null) {
                    toastShort("未获取到相关数据,请检查网络配置！");
                    log("未获取到相关数据,请检查网络配置！");
                    return;
                }
                if (response.body().getStatus() == 0) {

                    Product thisProduct = response.body().getData();

                    String productDetail = thisProduct.getDetail();
                    String[] split = productDetail.split("\\|");//将字符串转化为字符数组
                    imagePath = imagesPath(split, baseImgPath);//将链接前缀图片名称与拼接
                    initBanner(imagePath);
                    tvDetailPrice.setText("" + thisProduct.getPrice());
                    tvDetailDescription.setText(thisProduct.getName());


                } else {
                    toastShort("未获取相关数据");
                    log("未获取相关数据");
                }
            }

            @Override
            public void onFailure(Call<ServerResponse<Product>> call, Throwable t) {
                Log.d("request", "onFailure: ");
            }
        });
    }


//根据userId来获取其收货地址
    private void getAddress(int userId){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(RequestInterface.basePath)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        RequestInterface.ManageAddress requestInterfaceGetAddress = retrofit.create(RequestInterface.ManageAddress.class);
        Call<ServerResponse<AddressList>> call = requestInterfaceGetAddress.getAddrssList(userId);
        call.enqueue(new Callback<ServerResponse<AddressList>>() {

            @Override
            public void onResponse(Call<ServerResponse<AddressList>> call, Response<ServerResponse<AddressList>> response) {

                Log.d("detailsAddress", "成功");

                if (response.body() == null) {
                    toastShort("未获取到地址List数据,请检查网络配置！");
                    return;
                }
                if (response.body().getStatus() == 0) {

                    AddressList thisAddressList = response.body().getData();
                    String address = thisAddressList.getList().get(0).getFullAddress();
                    tvDetailAddress.setText(address);

                    Log.d("requestAddress", address);
                } else {
                    toastShort("请登录");
                }
            }

            @Override
            public void onFailure(Call<ServerResponse<AddressList>> call, Throwable t) {
                Log.d("request", "onFailure: ");
            }
        });
    }

//获取购物车的数量
    private void getShoppingCartList(int userId) {
        log("send request");
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(RequestInterface.basePath)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RequestInterface.CartRequest cartRequest = retrofit.create(RequestInterface.CartRequest.class);
        Call<ServerResponse<ShoppingCartList>> call = cartRequest.getShoppingCartList(userId);
        call.enqueue(new Callback<ServerResponse<ShoppingCartList>>() {

            @Override
            public void onResponse(Call<ServerResponse<ShoppingCartList>> call, Response<ServerResponse<ShoppingCartList>> response) {
                if (response.body().getStatus() == 0) {
                    log("success");
                    ShoppingCartList shoppingCartList = response.body().getData();
                    if (shoppingCartList != null) {
                        List<Cart> list = shoppingCartList.getCartProductVoList();
                        if (list != null && list.size() > 0){
                            num=0;
                            for(int i = 0; i < list.size(); i++) {
                                num += list.get(i).getQuantity();
                            }
                            badgeView.setBadgeCount(num);
                        }

                    }
                }
            }

            @Override
            public void onFailure(Call<ServerResponse<ShoppingCartList>> call, Throwable t) {
                toastShort("购物车加载失败，请检查网络");
            }
        });
    }
    //将商品添加到购物车中
    private void addToCart(int productId, int count, int useId) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(RequestInterface.basePath)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RequestInterface.Cart requestInterfaceCart = retrofit.create(RequestInterface.Cart.class);
        Call<ServerResponse> call = requestInterfaceCart.add(productId, count, useId);
        log("###addToCart:" + productId + " " + count + "  " + useId);

        call.enqueue(new Callback<ServerResponse>() {

            @Override
            public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) {

                if (response.body() == null) {
                    toastShort("未获取到相关数据,请检查网络配置！");
                    return;
                }
                if (response.body().getStatus() == 0) {
                    toastShort("添加成功！");
                    // 生成购物车“小圆点”
                    // TODO: 2019/1/1 0001  这里需要完善:点击加入购物车小圆点显示了，这时候点击
                    // TODO: 2019/1/1 0001  购物车进入购物车页面，在购物车页面返回到详情页，小圆点还在
                    badgeView = new BadgeView(thisActivty);
                    badgeView.setTargetView(thisActivty.findViewById(R.id.ll_detail_cart));
                    num++;
                    badgeView.setBadgeCount(num);

                } else {
                    toastShort("添加失败");
                }
            }

            @Override
            public void onFailure(Call<ServerResponse> call, Throwable t) {
                Log.d(TAG, "onFailure: ");
                toastShort("添加失败");
            }
        });
    }

}
